<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '#' }">
                运动会系统信息管理
            </el-breadcrumb-item>
            <el-breadcrumb-item>
                <a href="#">全能项目成绩标准</a>
            </el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="item-card">
            <el-row>
                <el-col class="co_sp1" :span="24">
                    <el-button type="primary" @click="importGradeExcel">导入</el-button>
                    <el-button type="primary" @click="unitExportExcel">导出</el-button>
                </el-col>
            </el-row>
            <el-table :data="currentPageData" border @current-change="handleRowClick" :highlight-current-row="true"
                ref="myTable">
                <el-table-column prop="dkey" label="编号" width="60" align="center">
                </el-table-column>
                <el-table-column prop="etname" label="项目" align="center">
                </el-table-column>
                <el-table-column prop="tbname" label="标识" align="center">
                </el-table-column>
                <el-table-column label="操作" width="250" align="center">
                    <template #default="scope">
                        <el-button type="success" @click="showelookdialog(scope.row)">查看</el-button>
                        <el-button type="primary" @click="showeditdialog(scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="paging" @size-change="handleSizeChange" @current-change="handlePageChange" background
                :page-sizes="[3, 5, 10, 15, 20, 50]" layout="total, prev, pager, next, jumper" :total="total"
                :page-size="queryObj.limit" :current-page="queryObj.page">
            </el-pagination>
            <!-- 导入 -->
            <el-dialog :title="seltable.etname + '成绩标准表 导入'" v-model="leadFileVisible" width="25%" draggable>
                <input type="file" class="dialog-inp" @change="handleFileUpload">
                <div slot="footer" class="dialog-footer">
                    <el-button @click="leadFileVisible = false">取 消</el-button>
                    <el-button type="primary" @click="uploadFile">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 查看页面 -->
            <el-dialog title="项目设置" v-model="lookdialogVisible" draggable width="50%" :before-close="handleBeforeClose">
                <div style="text-align: left;">
                    <el-button type="primary" @click="addbtn">添加</el-button>
                </div>
                <el-table :data="scoreData" border height="52vh" ref="tableContainer">
                    <el-table-column prop="dfmark" label="分数" align="center">
                        <template #default="scope">
                            {{ scope.row.b }}
                        </template>
                    </el-table-column>
                    <el-table-column label="成绩" align="center">
                        <template #default="scope">
                            {{ scope.row.time }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button type="primary" @click="dfeditdialog(scope.row)">修改</el-button>
                            <el-button type="danger" @click="dfdelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>

            <!-- 修改页面 -->
            <el-dialog title="项目设置" v-model="editdialogVisible" draggable width="30%" :before-close="handleClose">
                <el-form :model="editfrom">
                    <el-form-item label="项目：">
                        <el-input v-model="editfrom.etname"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelEdit">取 消</el-button>
                    <el-button type="primary" @click="editIteminfo">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 得分添加页面 -->
            <el-dialog title="得分添加" v-model="addDefendialogVisible" draggable width="15%">
                <el-form :model="addDefenfrom">
                    <el-form-item label="成绩：">
                        <el-input v-model="addDefenfrom.b"></el-input>
                    </el-form-item>
                    <el-form-item label="分数：">
                        <el-input v-model="addDefenfrom.time"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addDefendialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addgn">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 得分修改页面 -->
            <el-dialog title="得分修改" v-model="editDefendialogVisible" draggable width="15%">
                <el-form :model="editDefenfrom">
                    <el-form-item label="成绩：">
                        <el-input v-model="editDefenfrom.b"></el-input>
                    </el-form-item>
                    <el-form-item label="分数：">
                        <el-input v-model="editDefenfrom.time"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDefendialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmEdit">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
    components: {
        XLSX,
    },
    data() {
        return {
            queryObj: {
                limit: 10,
                page: 1,
                query: " "
            },
            total: 0,
            currentPageData: [],
            leadFileVisible: false,
            inpItemName: null,
            itemData: [],
            editdialogVisible: false,
            editfrom: {
                itemname: '',
            },
            lookdialogVisible: false,
            seltable: {},
            tableval: -1,
            scoreData: [],
            // scoreedit:true,
            defendkey: '',
            addDefendialogVisible: false,
            addDefenfrom: {
                a: null,
                b: null,
                time: '00:00:00.000',
                tbname: '',
            },
            editDefendialogVisible: false,
            editDefenfrom: {},
            formData: null,
            originalData: [],
            loading: false
        }
    },
    created() {
        this.getItemgradeList()
    },
    methods: {
        async getItemgradeList() { // 数据
            try {
                const result = await this.$http.post(this.BACKEND_URL + '/deifen/getmsg');
                if (result.data.code == 0) {
                    this.itemData = result.data.data
                    this.$refs.myTable.setCurrentRow(this.itemData[0]);
                    this.total = this.itemData.length
                    this.fetchData()
                } else if (result.data.code == 500) {
                    console.log(result.data.msg)
                }
            } catch (error) {
                if (error === undefined) {
                    this.$message.error('连接错误-获取数据失败');
                }
            }
        },
        // 获取单个数据信息
        async showeditdialog(info) {
            this.editdialogVisible = true
            this.editfrom = info
        },
        async editIteminfo() {
            const result = await this.$http.post(this.BACKEND_URL + '/deifen/updatemsg', this.editfrom)
            if (result.data.code == 0) {
                this.editdialogVisible = false
                this.getItemgradeList()
                this.$message.success('修改成功')
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        cancelEdit() {
            this.editdialogVisible = false
            this.getItemgradeList()
        },
        handleClose(done) {
            this.getItemgradeList()
            done()
        },
        // 转化记录时间格式
        formatTime(value) {
            const [hours, minutes, seconds] = value.split(':');
            const milliseconds = (parseInt(hours, 10) * 3600 + parseInt(minutes, 10) * 60 + parseFloat(seconds)) * 1000;
            return milliseconds
        },
        // 点击获取表格数据
        handleRowClick(row) {
            this.defendkey = row.tbname
            this.seltable = row
        },
        // 查看
        async showelookdialog(val) {
            this.lookdialogVisible = true;
            const result = await this.$http.post(this.BACKEND_URL + '/fen/getmsg', val);
            if (result.data.code == 0) {
                let newData = result.data.data.map(item => ({ ...item, b: (item.b / 10).toFixed(1) }));
                this.scoreData = newData.slice(0, 100);
                this.originalData = newData;
                this.$refs.tableContainer.$refs.bodyWrapper.addEventListener('scroll', this.handleScroll, true);
            } else if (result.data.code == 500) {
                this.scoreData = []
                console.log(result.data.msg)
            }
        },
        handleScroll(res) {
            const height = res.target;
            const clientHeight = height.clientHeight;
            const scrollTop = height.scrollTop;
            const scrollHeight = height.scrollHeight;
            if (clientHeight + scrollTop === scrollHeight) {
                this.checkBottom();
            }
        },
        async checkBottom() {
            if (this.originalData.length > this.scoreData.length) {
                const startIndex = this.scoreData.length;
                const endIndex = Math.min(startIndex + 100, this.originalData.length);
                const additionalData = this.originalData.slice(startIndex, endIndex);
                this.scoreData = [...this.scoreData, ...additionalData];
            } else {
                console.log('数据加载完毕');
            }
        },
        handleBeforeClose(done) {
            this.$refs.tableContainer.scrollTo(0, 0);
            this.$refs.tableContainer.$refs.bodyWrapper.removeEventListener('scroll', this.handleScroll, true);
            this.scoreData = []
            done()
        },
        // 查看-修改
        dfeditdialog(c) {
            this.editDefendialogVisible = true
            this.editDefenfrom = c
            this.editDefenfrom.tbname = this.defendkey
            this.editDefenfrom.oldA = this.editDefenfrom.a
        },
        async confirmEdit() {
            this.editDefenfrom.b = this.editDefenfrom.b * 10
            this.editDefenfrom.a = this.formatTime(this.editDefenfrom.time)
            const result = await this.$http.post(this.BACKEND_URL + '/fen/updatemsg', this.editDefenfrom)
            if (result.data.code == 0) {
                this.editDefendialogVisible = false
                this.showelookdialog(this.seltable)
                this.$message.success('修改成功')
            } else if (result.data.code == 500) {
                this.showelookdialog(this.seltable)
                this.$message.error(result.data.msg)
            }
        },
        // 查看-新增
        addbtn() {
            this.addDefendialogVisible = true
            this.addDefenfrom.tbname = this.defendkey
        },
        async addgn() {
            this.addDefenfrom.b = this.addDefenfrom.b * 10
            this.addDefenfrom.a = this.formatTime(this.addDefenfrom.time)
            const result = await this.$http.post(this.BACKEND_URL + '/fen/insertmsg', this.addDefenfrom)
            if (result.data.code == 0) {
                this.addDefendialogVisible = false
                this.showelookdialog(this.seltable)
                this.$message.success('添加成功')
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        // 查看-删除
        dfdelete(ind) {
            this.$confirm('此操作将删除改条数据，是否继续', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(async () => {
                const result = await this.$http.post(this.BACKEND_URL + '/fen/deletemsg', { tbname: this.defendkey, a: ind.a })
                if (result.data.code === 0) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.showelookdialog(this.seltable)
                } else if (result.data.code == 500) {
                    this.$message.error(result.data.msg)
                }
            }).catch(() => {
            });
        },
        // 导入
        importGradeExcel() {
            this.leadFileVisible = true
        },
        handleFileUpload(e) {
            let file = e.target.files[0]
            this.formData = new FormData()
            this.formData.append('file', file);
            this.formData.append('etname', this.seltable.etname);
        },
        async uploadFile() {
            const result = await this.$http.post(this.BACKEND_URL + '/deifen/excel', this.formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            if (result.data.code == 0) {
                this.leadFileVisible = false
                this.showelookdialog(this.seltable)
                this.$message({
                    type: 'success',
                    message: '导入成功!'
                });
            } else if (result.data.code == 500) {
                this.$message({
                    type: 'error',
                    message: '导入失败!'
                });
                console.log(result.data.msg)
            }
        },
        // 导出
        async unitExportExcel() {
            try {
                const result = await this.$http.get(this.BACKEND_URL + '/fen/export', {
                    params: { etname: this.seltable.etname },
                    responseType: 'blob',
                });

                let downloadUrl = window.URL.createObjectURL(new Blob([result.data]));

                const link = document.createElement('a');
                link.href = downloadUrl;
                link.setAttribute('download', this.seltable.etname + '成绩标准.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } catch (error) {
                console.error('File export failed:', error);
            }
        },
        // 分页
        fetchData() {
            let startIndex = (this.queryObj.page - 1) * this.queryObj.limit;
            let endIndex = startIndex + this.queryObj.limit;
            this.currentPageData = this.itemData.slice(startIndex, endIndex);
            this.$refs.myTable.setCurrentRow(this.currentPageData[0]);
        },
        handleSizeChange(newSize) {
            this.queryObj.limit = newSize
        },
        handlePageChange(newPage) {
            this.queryObj.page = newPage;
            let startIndex = (newPage - 1) * this.queryObj.limit;
            let endIndex = startIndex + this.queryObj.limit;
            this.currentPageData = this.itemData.slice(startIndex, endIndex);
            this.$refs.myTable.setCurrentRow(this.currentPageData[0]);
        }
    }
}
</script>

<style lang="less" scoped>
.item-card {
    margin-top: 15px;

    .el-table {
        margin-top: 15px;
    }

    .co_sp1 {
        text-align: left;
    }
}

.dialog-inp {
    border: 1px solid #ccc;
}

.dialog-footer {
    margin-top: 15px;
    color: #c6bed1;
}

.paging {
    margin-top: 15px;
}
</style>